﻿using sMES_Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using sMES_Base.service;
using exe_machine_check_process.Modules;
using exe_machine_check_process.Models;
using System.Data;

namespace exe_machine_check_process
{
    /// <summary>
	/// 元件[exe_machine_check_process]
    /// <auth>gracecai</auth><time>2018/12/4 下午 03:40:57</time>
    /// <description></description>
    /// <list>
    ///     <modify>
    ///         <auth></auth><mantis></mantis><time></time>
    ///         <description></description>
    ///     </modify>
    /// </list>
    /// </summary>
    public class exe_machine_check_process_utility : BaseUtility
    {
        public exe_machine_check_process_utility(ref BaseService CurrentService) : base(ref CurrentService)
        {
        }
        //20210609 Modify by德義家興for#91011: 
        public void multi_equipment_dispatch_area_info_set(RequestContent content)
        {
            StringBuilder sbSQL = new StringBuilder();
            foreach (var item in content.selected_EquipmentList)
            {
                //20210609 add by德義家興for#91011: 檢查該設備是否有設定該檢查表;有才執行後面的邏輯
                //20210616 modify by德義家興for#91011: 使用parameter
                Dictionary<string, object> _params = new Dictionary<string, object>();
                _params.Add("EquipmentNo", item);
                _params.Add("EquipmentCheckUpRate", content.qc_frequency);
                sbSQL.Clear();
                sbSQL.Append("  SELECT COUNT(* )FROM tblEQPEquipmentCheckUpRate ");
                sbSQL.Append("  WHERE EquipmentNo = ? ");
                sbSQL.Append("  AND IsEnabled=1  ");
                sbSQL.Append("  AND EquipmentCheckUpRate = ? ");
                int? result = CurrentService.GetDao().Query1RecordInt(Convert.ToString(sbSQL), _params);
                //檢查是否有查詢結果
                if (!(result == 0) )
                {
                    content.machine_no = item;
                    dispatch_area_info_set(content);
                }
            }
        }
        public void dispatch_area_info_set(RequestContent content)
        {
            DataTable dt_tblWIPEQPQCDetail, dt_tblEQPQCDetail,dt = new DataTable();

            CDO_exe_machine_check_process parsObj;
            string QCListSerial;
            bool bCheckDataSuccess = false;
            DataRow drAdd;

            ////'Initial
            string strSQL = "Select * From tblWIPEQPQCListDetail Where 1<>1";
            dt_tblWIPEQPQCDetail= CurrentService.GetDao().Query(strSQL);

            ////取得設備點檢表
            StringBuilder sbTemp = new StringBuilder("Select * From tblEQPQCListDetail ");
            sbTemp.Append("Where QCListNo = '" + content.checklist_no + "' ");
            dt_tblEQPQCDetail = CurrentService.GetDao().Query(sbTemp.ToString());

            //// 取得QCListSerial
            parsObj = new CDO_exe_machine_check_process();
            parsObj.QCListSerial = content.checklist_no + DateTime.Now.ToString("yyMMdd");
            parsObj.QCResult = "0";
            QCListSerial = GetQCListSerial(parsObj);

            parsObj.qc_frequency = content.qc_frequency;

            //'將點檢資訊整理成AddWIPEQPQCListLog要用的資料樣式
            foreach (CDO_machine_check_process_checklist_detail abnormalDetail in content.checklist_detail)
            {
                bCheckDataSuccess = true;

                //'取得MDS檢點資訊
                DataRow[] drSEL = dt_tblEQPQCDetail.Select("QCOrder = '" + abnormalDetail.item_no + "'");
                if (drSEL.Length<=0) {continue;}

                //'資料檢核
                //'2018/09/06 KunYuan：點檢表新增文字類型，故不在檢查檢驗結果，因為可能有空值狀態，由於db欄位為必填故預設check_result = 0  (Mantis No：0046952)
                if (string.IsNullOrEmpty(abnormalDetail.check_result)) { abnormalDetail.check_result = "0"; } 
                if ((!string.IsNullOrEmpty(abnormalDetail.check_result)) & abnormalDetail.check_result == "1") { parsObj.QCResult = "1"; } 
                if (string.IsNullOrEmpty(abnormalDetail.check_value))  { bCheckDataSuccess = false; }

                if (!bCheckDataSuccess) { continue; }

                drAdd = dt_tblWIPEQPQCDetail.NewRow();
                drAdd["QCListSerial"] = QCListSerial;
                drAdd["QCItem"] = drSEL[0]["QCItem"];
                drAdd["QCResult"] = abnormalDetail.check_result;
                drAdd["InputValue"] = abnormalDetail.check_value;
                drAdd["STDValue"] = drSEL[0]["STDValue"];
                drAdd["MaxiValue"] = drSEL[0]["MaxiValue"];
                drAdd["MiniValue"] = drSEL[0]["MiniValue"];
                drAdd["InputDataCount"] = drSEL[0]["InputDataCount"];
                drAdd["QCOrder"] = drSEL[0]["QCOrder"];
                drAdd["QCType"] = drSEL[0]["QCType"];
                dt_tblWIPEQPQCDetail.Rows.Add(drAdd);

            }

            ////'Add QC Result
            parsObj.QCListSerial = QCListSerial;
            parsObj.EquipmentNo = content.machine_no;
            //parsObj.QCResult = "0";
            parsObj.QCListNo = content.checklist_no;
            parsObj.checklist_detail = dt_tblWIPEQPQCDetail;

            parsObj.handle_user_no = content.handle_user_no;    
            parsObj.handle_time = content.handle_time;

            AddWIPEQPQCListLog(parsObj);

        }

        /// <summary>
        /// 取得QCListSerial
        /// </summary>
        /// <returns>單號(「點檢表編號(QCLISTNO)」+「建立日(CREATEDATE)」 + XXX 流水號)</returns>
        private String GetQCListSerial(CDO_exe_machine_check_process parsObject)
        {

            DataTable dt = new DataTable();

            string strSQL = "Select QCListSerial From tblWIPEQPQCListLog " +
                     " Where QCListSerial like '" + parsObject.QCListSerial + "%' " +
                     " Order by QCListSerial desc";
            dt = CurrentService.GetDao().Query(strSQL);
            if (dt.Rows.Count > 0)
            {
                string strLastSerial = (Convert.ToString(dt.Rows[0]["QCListSerial"]));
                string strNewSerial;
                int intLastSrequence = 1;

                int i = 1;
                //規則為  「點檢表編號(QCLISTNO)」+「建立日(CREATEDATE)」 +XXX 流水號
                intLastSrequence = Convert.ToInt16(strLastSerial.Substring(strLastSerial.Length - 3, 3)) + 1;//+ System.Threading.Thread.CurrentThread.ManagedThreadId).PadLeft(5, '0');
                strNewSerial = strLastSerial.Substring(0, strLastSerial.Length - 3) + intLastSrequence.ToString("000");//.PadLeft(3, '0');


                return strNewSerial;
            }
            else
            {
                return parsObject.QCListSerial + "001";
            }


        }

        /// <summary>
        /// 取得檢驗單號
        /// </summary>
        /// <returns>新增 WIPEQPQCListLog 紀錄，同時處理單頭與單身僅有 QCResult = 0 , 1 時，才處理設備狀態
        private void AddWIPEQPQCListLog(CDO_exe_machine_check_process parsObject)
        {
            string strSQL;
            DateTime CreateDate = DateTime.Now;

            //'處理設備狀態
            if (parsObject.QCResult.Equals(1))
            {
                //將目前的現況轉至Log
                DataTable dt;
                strSQL = "Select * From tblEMSEquipmentState Where EquipmentNo ='" + parsObject.EquipmentNo + "'";
                dt = CurrentService.GetDao().Query(strSQL);
                

                if (dt.Rows.Count > 0)
                {
                    string strDescription = "";

                    strSQL = "Insert into tblEMSEquipmentStateLog (EQPSerialNo,EquipmentNo,EquipmentState,EquipmentType,UserNo,Description,StartTime,EndTime) " +
                              "Values ('" + dt.Rows[0]["EQPSerialNo"] + "','" + parsObject.EquipmentNo + "'," + dt.Rows[0]["EquipmentState"] + ",'" + dt.Rows[0]["EquipmentType"] + "','" + dt.Rows[0]["UserNo"] + "','" +
                              strDescription + "',SYSDATE ,SYSDATE)";
                    CurrentService.GetDao().ExecuteNonQuery(strSQL);

                    string EQPSerialNo;
                    //string SerialNo;
                    Int16 intUpperBound = 1;
                    Int16 intLowerBound = 999;
                    Int16 intRandomValue = 0;
                    DateTime datEventTime = DateTime.Now;

                    Int16 InitEQPSerialNo;
                    Random rnd = new Random();
                    InitEQPSerialNo= Convert.ToInt16(rnd.Next(intUpperBound, intLowerBound) + intLowerBound);


                    EQPSerialNo = (System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()).PadRight(2).PadLeft(2, '0');
                    EQPSerialNo += intRandomValue.ToString("000");
                }
            }



            //'加入Log
            //'先加入必要欄位
            string strFieldList = "INSERT INTO tblWIPEQPQCListLog(QCListSerial";
            string strValueList = " VALUES('" + parsObject.QCListSerial + "'";

            if (parsObject.EquipmentNo != null)
            {
                strFieldList += ", EquipmentNo";
                strValueList += ",'" + parsObject.EquipmentNo + "'";
            }

            if (parsObject.QCListNo != null)
                strFieldList += ", QCListNo";
            strValueList += ",'" + parsObject.QCListNo + "'";

            if (parsObject.QCResult != null)
                strFieldList += ", QCResult";
            strValueList += "," + parsObject.QCResult;

            if (CreateDate != null)
                strFieldList += ", CreateDate";
            strValueList += ", SYSDATE" ;

            if (CreateDate != null)
                strFieldList += ", CREATOR";
            strValueList += ", '" + BaseService._ServiceInfo.account + "'";

            if (parsObject.qc_frequency  != null)
            {
                strFieldList += ", EquipmentCheckUpRate";
                strValueList += ",'" + parsObject.qc_frequency + "'";
            }

            if (parsObject.handle_user_no != null)
            {
                strFieldList += ", handle_user_no_C";
                strValueList += ",'" + parsObject.handle_user_no + "'";
            }

            if (parsObject.handle_time != null)
            {
                strFieldList += ", handle_time_C";
                strValueList += ",'" + parsObject.handle_time + "'";
            }

            //'組合SQL Statement
            strSQL = strFieldList + ")" + strValueList + ")";
            //執行SQL
            CurrentService.GetDao().ExecuteNonQuery(strSQL);

            //'Add tblWIPEQPQCListDetail
            if (parsObject.checklist_detail.Rows.Count!=0)
            {
                for (int i = 0; i < parsObject.checklist_detail.Rows.Count; i++)
                {
                    String strDetailField = "Insert Into tblWIPEQPQCListDetail (QCListSerial, QCItem, QCResult";
                    String strDetailValue="";

                    strDetailValue = String.Format(" VALUES('{0}','{1}',{2}", parsObject.checklist_detail.Rows[i]["QCListSerial"], parsObject.checklist_detail.Rows[i]["QCItem"],
                                    parsObject.checklist_detail.Rows[i]["QCResult"]);

                    if (!String.IsNullOrEmpty(Convert.ToString(parsObject.checklist_detail.Rows[i]["InputValue"])))
                    {
                        strDetailField += ",InputValue ";
                        strDetailValue += ",'" + Convert.ToString(parsObject.checklist_detail.Rows[i]["InputValue"]) + "'";

                    }
                    if (!String.IsNullOrEmpty(Convert.ToString(parsObject.checklist_detail.Rows[i]["StdValue"])))
                    {
                        strDetailField += ",StdValue ";
                        strDetailValue += ",'" + Convert.ToString(parsObject.checklist_detail.Rows[i]["StdValue"]) + "'";

                    }
                    if (!String.IsNullOrEmpty(Convert.ToString(parsObject.checklist_detail.Rows[i]["InputValue"])))
                    {
                        strDetailField += ",MaxiValue ";
                        strDetailValue += ",'" + Convert.ToString(parsObject.checklist_detail.Rows[i]["MaxiValue"]) + "'";

                    }
                    if (!String.IsNullOrEmpty(Convert.ToString(parsObject.checklist_detail.Rows[i]["MaxiValue"])))
                    {
                        strDetailField += ",MiniValue ";
                        strDetailValue += ",'" + Convert.ToString(parsObject.checklist_detail.Rows[i]["MiniValue"]) + "'";

                    }
                    if (!String.IsNullOrEmpty(Convert.ToString(parsObject.checklist_detail.Rows[i]["InputDataCount"])))
                    {
                        strDetailField += ",InputDataCount ";
                        strDetailValue += ",'" + Convert.ToString(parsObject.checklist_detail.Rows[i]["InputDataCount"]) + "'";

                    }
                    if (!String.IsNullOrEmpty(Convert.ToString(parsObject.checklist_detail.Rows[i]["QCOrder"])))
                    {
                        strDetailField += ",QCOrder ";
                        strDetailValue += "," + Convert.ToString(parsObject.checklist_detail.Rows[i]["QCOrder"]) ;

                    }
                    if (!String.IsNullOrEmpty(Convert.ToString(parsObject.checklist_detail.Rows[i]["QCType"])))
                    {
                        strDetailField += ",QCType ";
                        strDetailValue += "," + Convert.ToString(parsObject.checklist_detail.Rows[i]["QCType"]) ;

                    }
                    strSQL = strDetailField + ")" + strDetailValue + ")";
                    CurrentService.GetDao().ExecuteNonQuery(strSQL);
                }
                

            }

        }
    }
}
